import config from "../config"
const USER_TOKEN_KEY = 'USER_TOKEN_KEY';

const getToken = function() {
	let ret = '';
	ret = uni.getStorageSync(USER_TOKEN_KEY);
	if (!ret) {
		ret = '';
	}
	return ret;
}

const setToken = function(token) {
	uni.setStorageSync(USER_TOKEN_KEY, token);
}

const Request = function(method, url, data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.host + url,
			method: method,
			data: data,
			header: {
				"Authorization": "Bearer " + getToken(),
			},
			success: (res) => {
				console.log("request success", res)
				resolve(res)
			},
			fail: (res) => {
				console.log("request fail", res)
				reject(res)
			},
			complete: () => {
				console.log("request finally")
			}
		});
	})
}

const FormRequest = function(method, url, data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.host + url,
			method: method,
			data: data,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"Authorization": "Bearer " + getToken(),
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (res) => {
				reject(res)
			},
			complete: () => {
			}
		});
	})
}

export default {
	Request: Request,
	FormRequest: FormRequest,
	setToken: setToken
}